<template>
  <div class="login-container">
    <div class="tabs-wrapper">
      <el-tabs v-model="activeName" @tab-click="handleClick">

        <el-tab-pane label="密码登录" name="login">
          <div class="input-wrapper">
            <input type="text" :class="isLoginFail ? 'error-input': ''" v-model="username" placeholder="手机号/邮箱/用户名" @change="checkLogin"/>
          </div>
          <div class="input-wrapper">
            <input :type="isCheckPassword ? 'text' : 'password'" :class="isLoginFail ? 'error-input': ''" v-model="password" placeholder="密码" show-password @change="checkLogin"/>
            <div class="check-password" @click="isCheckPassword= !isCheckPassword">
              <i class="el-icon-open" v-if="isCheckPassword"></i>
              <i class="el-icon-turn-off" v-else></i>
            </div>
          </div>
          <div class="error-info">
            <span v-if="isLoginFail">用户名或密码错误</span>
            <a href="#" class="forget" v-if="isLoginFail">忘记密码</a>
          </div>
          <div :class="unableLogin ? 'login-btn forbid' : 'login-btn no-forbid'" @click="login">登录</div>
          <div class="to-home"><router-link to="/home">直接去博客首页</router-link></div>
        </el-tab-pane>

        <el-tab-pane label="用户注册" name="register">
          <el-form :model="userInfoForm" :rules="userInfoFormRules" ref="userInfoForm">
            <el-form-item prop="username">
              <el-input v-model="userInfoForm.username" placeholder="用户名" autocomplete="on"></el-input>
            </el-form-item>
            <el-form-item prop="phone">
              <el-input v-model="userInfoForm.phone" placeholder="手机号"></el-input>
            </el-form-item>
            <el-form-item prop="email">
              <el-input v-model="userInfoForm.email" placeholder="邮箱"></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="userInfoForm.password" placeholder="密码" show-password autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item prop="checkPassword">
              <el-input v-model="userInfoForm.checkPassword" placeholder="确认密码" show-password autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm('userInfoForm')">注册</el-button>
              <el-button @click="resetForm('userInfoForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>

  </div>
</template>

<script>
export default {
  name: "Login",
  data() {
    let validateMobileNumber= (rule, value, callback) => {
      if (!value) {
        return new Error("请输入手机号");
      } else {
        const reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
        const isPhone = reg.test(value);
        value = Number(value); //转换为数字
        if (typeof value === "number" && !isNaN(value)) {//判断是否为数字
          value = value.toString(); //转换成字符串
          if (value.length < 0 || value.length > 12 || !isPhone) { //判断是否为11位手机号
            callback(new Error("手机号码格式如:138xxxx8754"));
          } else {
            callback();
          }
        } else {
          callback(new Error("请输入手机号"));
        }
      }
    };
    let validateEmail = (rule, value, callback) => {
      if (!value) {
        callback();
      } else {
        const reg = /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/;
        const email = reg.test(value);
        if (!email) {
          callback(new Error("邮箱格式如:admin@163.com"));
        } else {
          callback();
        }
      }
    };
    let validatePassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.userInfoForm.checkPassword !== '') {
          this.$refs.userInfoForm.validateField('checkPassword');
        }
        callback();
      }
    };
    let validateCheckPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入确认密码'));
      } else if (value !== this.userInfoForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };

    return {
      activeName: 'login',

      // 用户登录
      username: '',
      password: '',
      unableLogin: true,   // 控制登录按钮的样式
      isLoginFail: false,  // 是否登录失败
      isCheckPassword: false,  // 是否查看密码

      // 用户注册
      userInfoForm: {
        username: '',
        phone: '',
        email: '',
        password: '',
        checkPassword: '',
      },
      userInfoFormRules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
        ],
        phone: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {validator: validateMobileNumber, trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          {validator: validateEmail, trigger: 'blur'}
        ],
        password: [
          {validator: validatePassword, trigger: 'blur'}
        ],
        checkPassword: [
          {validator: validateCheckPassword, trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    handleClick(tab, event) {
      // console.log(tab, event);
    },
    checkLogin() {
      this.isLoginFail= false;
      if(this.username && this.password) {
        this.unableLogin= false;
        return ;
      }
      this.unableLogin= true;
    },
    // 登录
    login() {
      if(!this.username || !this.password) {
        this.unableLogin= true;
        this.isLoginFail= false;
        return ;
      }
      let _this= this;
      this.$http({
        url: '/admin/login',
        method: 'get',
        params: {
          username: _this.username,
          password: _this.password
        },
        // withCredentials: true //跨域请求是否提供凭据信息(cookie、HTTP认证及客户端SSL证明等),也可以简单的理解为，当前请求为跨域类型时是否在请求中协带cookie
      }).then(response=>{
        let res= response.data;
        if(res.code===200) {
          this.$message.success('登录成功！跳转至后台管理页');
          _this.$router.replace('/admin');
          window.sessionStorage.setItem('userInfo', JSON.stringify(res.data));
          this.isLoginFail= false;
        } else {
          this.$message.error('登录失败！');
          this.isLoginFail= true;
        }
      });
    },


    // 注册
    submitForm(formName) {
      let _this= this;
      // console.log(this.userInfoForm);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          _this.$http({
            url: '/admin/register',
            method: 'post',
            data: _this.userInfoForm,
            // withCredentials: true //跨域请求是否提供凭据信息(cookie、HTTP认证及客户端SSL证明等),也可以简单的理解为，当前请求为跨域类型时是否在请求中协带cookie
          }).then(response=>{
            let res= response.data;
            if(res.code===200) {
              this.$message.success('注册成功！跳转至后台管理页');
              _this.$router.replace('/admin');
              window.sessionStorage.setItem('userInfo', JSON.stringify(res.data));
            } else if(res.code===202) {
              this.$message.warning(`注册失败！${res.msg}`);
            } else {
              this.$message.error('注册失败！');
            }
          })
        } else {
          this.$message.error('注册失败！');
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>

<style scoped lang="less">
  .login-container {
    position: relative;
    width: 100%;
    height: 100%;
    background-image: linear-gradient(to right, #397CA5, #343E43);

    .tabs-wrapper {
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      margin: auto;

      width: 50%;
      height: 450px;
      background: #fff;
      border-radius: 10px;
      padding: 20px;
      box-sizing: border-box;

      .input-wrapper, .login-btn, .login-btn2 {
        width: 100%;
        position: relative;
        font-size: 14px;
        display: inline-block;
        line-height: 40px;
        margin-bottom: 22px;

        input {
          width: 100%;
          height: 40px;
          line-height: 40px;
          padding: 0 15px;
          border-radius: 4px;
          border: 1px solid #DCDFE6;
          box-sizing: border-box;
          color: #606266;
          outline: 0;
          &.error-input {
            border-color: #F56C6C;
          }
        }
      }
      .input-wrapper {
        position: relative;
        .check-password {
          width: 40px;
          height: 40px;
          text-align: center;
          position: absolute;
          top: 0;
          right: 0;
          cursor: pointer;
        }
      }

      .error-info {
        color: #F56C6C;
        font-size: 12px;
        height: 20px;
        line-height: 20px;
        margin: -18px 0 4px 0;
        a.forget {
          float: right;
          cursor: pointer;
        }
      }
      .login-btn {
        text-align: center;
        border-radius: 4px;
        cursor: pointer;
        color: #fff;
        font-size: 18px;
        letter-spacing: 4px;
        &.forbid {
          background: #EE9B86;
        }
        &.no-forbid {
          background: #F63D15;
        }
      }
      .to-home {
        text-align: center;
        border-radius: 4px;
        cursor: pointer;
        color: #fff;
        font-size: 18px;
        letter-spacing: 4px;
        background: #24ADF3;
        line-height: 40px;
        height: 40px;
        margin-top: 10px;
        a {
          display: inline-block;
          width: 100%;
          height: 100%;
          color: #fff;
          text-decoration: none;
        }
      }
    }

    /* 当浏览器的可视区域小于650px */
    @media screen and ( max-width: 650px ) {
      .tabs-wrapper {width: 90%;}
    }
  }
</style>
